﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitBase.WinForm;
using YJKRevitKernel.RevitViewUtility;
using YJKMenuAssist.Commands;

namespace YJKMenuAssist
{
	public class CmdsExternalEventHandler : IExternalEventHandler
	{
		public void SetFamilySymbolType(string strFamilyName = null, string strFSType = null)
		{
			this.m_strFamilyName = strFamilyName;
			this.m_strFSType = strFSType;
		}

		public ExternalCommandData CommandData
		{
			set
			{
				this.m_CommandData = value;
			}
		}

		public CommandInfos CurrentCmdInfos
		{
			set
			{
				this.m_CurrentCmdInfos = value;
			}
		}

		public CmdsExternalEventHandler(ExternalCommandData commandData, ElementSet elements)
		{
			this.m_CommandData = commandData;
			this.m_Elements = elements;
		}

		public void Execute(UIApplication app)
		{
			this.m_Message = "";
			try
			{
				if (this.m_CurrentCmdInfos != null)
				{
					if (ExternalCommandShowPage._hWndRevit == null)
					{
						ExternalCommandShowPage._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
					}
					int wMsg = 7;
					CmdsExternalEventHandler.SendMessage(ExternalCommandShowPage._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
					GetUIView.SetRevitWorkWindowFocused(app.ActiveUIDocument.Document);
					if (this.m_CurrentCmdInfos.DllName != "")
					{
						Assembly executingAssembly = Assembly.GetExecutingAssembly();
						(Assembly.LoadFrom(executingAssembly.Location.Remove(executingAssembly.Location.LastIndexOf("\\")) + "\\" + this.m_CurrentCmdInfos.DllName).CreateInstance(this.m_CurrentCmdInfos.ClassName) as IExternalCommand).Execute(this.m_CommandData, ref this.m_Message, this.m_Elements);
					}
					else
					{
						this.m_CommandData.Application.PostCommand(RevitCommandId.LookupCommandId(this.m_CurrentCmdInfos.CmdId));
					}
				}
			}
			catch (Exception ex)
			{
				TaskDialog.Show("R", ex.Message);
				this.m_CurrentCmdInfos = null;
			}
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public string GetName()
		{
			return "CmdsExternalEventHandler";
		}

		private ExternalCommandData m_CommandData;

		private string m_Message = "";

		private ElementSet m_Elements;

		private CommandInfos m_CurrentCmdInfos;

		private string m_strFSType;

		private string m_strFamilyName;
	}
}
